import { Component, OnInit, OnDestroy } from '@angular/core';
import { NavController, NavParams } from '@ionic/angular';
import { DataService } from '@services/data.service';
import { DeviceIndexCircleService } from '@services/chart.service';
import { DeviceEchartsService } from '@services/echarts/device.echarts.service';
import { ActivatedRoute } from '@angular/router';
import { EmitService } from '@services/emit.service';
import { DatePipe } from '@angular/common';
import { Observable } from 'rxjs';


interface Parameter {
  value: '';
  unit: '';
  hasAlarm;
}

interface DeviceParameterGroup {
  projectId: '';
  name: '';
  unit: '';
  deviceId: '';
  deviceTypeId: '';
  values: Array<Parameter>;
  datacodes: any;
  Position: any;
}

@Component({
  selector: 'page-device',
  templateUrl: 'device.html',
  providers: [DeviceIndexCircleService],
  styleUrls: ['device.scss'],
})
export class DevicePage implements OnInit, OnDestroy {
  options;
  deviceID;
  deviceTypeCode;
  deviceName;
  parameters;
  onlineStatus = 0;
  hasAlarms = false;
  projectDeviceParams: any[];
  showRateChart = true;
  circleImgSrc;

  toDay;  // 前一天
  nextDay;  // 后一天
  Days;      // 总天数



  buttonsData = [
    { id: 4, name: '设备台账', state: false },
    { id: 5, name: '运行记录', state: false },
    { id: 6, name: '控制', state: false },
  ];

  deviceList;
  areaName;
  deviceIndex;

  parameterGroup = {
    parameterGroup_1: [],
    parameterGroup_2: [],
  };

  showParamesCurvNow;  // 判断当前点击的历史曲线项

  parameterGroup_10: DeviceParameterGroup;
  // 默认显示在图表内的参数
  parameterGroup_11: DeviceParameterGroup;

  _refreshInterval;

  titles = { left: '' };
  state = {
    reset: true,
  };

  constructor(
    public navCtrl: NavController,
    public dataservice: DataService,
    public chart: DeviceIndexCircleService,
    public echart: DeviceEchartsService,
    public activatedRoute: ActivatedRoute,
    public emitService: EmitService,
    public datePipe: DatePipe
  ) {
    // this.activatedRoute.queryParams.subscribe(params => {
    //   console.log(params);
    //   this.deviceID = params.deviceID;
    //   this.areaName = params.areaName;
    //   this.deviceIndex = parseInt(params.deviceIndex, 10);
    // });
    const devices = this.emitService.deviceParams;
    this.deviceID = devices.deviceID;
    this.deviceIndex = parseInt(devices.deviceIndex, 10);
    this.areaName = devices.areaName;

    this.deviceList = {
      list: [],
      aim: this.deviceIndex,
    };

    let tempList; tempList = [];
    for (let m = 0; m < devices.devices.length; m++) {
      if (devices.devices[m]) {
        const element = devices.devices[m];
        tempList.push({
          RoomName: element.deviceName,
          deviceId: element.deviceId,
        });
      }
    }
    this.deviceList.list = tempList;
    console.log(this.deviceList);
  }

  ngOnInit() {
    this.toDay = this.datePipe.transform(new Date(), 'yyyy-MM-dd');
    const nextday = + new Date() + 1000 * 60 * 60 * 24;
    this.nextDay = this.formatDate(new Date(nextday), 'yyyy-MM-dd');
    this.getDeviceInfo(this.deviceID);
    this._refreshInterval = setInterval(() => {
      this.getDeviceInfo(this.deviceID);
    }, 10000);

  }

  ngOnDestroy() {
    if (this._refreshInterval) {
      clearInterval(this._refreshInterval);
    }
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad DevicePage');
  }

  doRefresh(refresher) {
    this.getDeviceInfo(this.deviceID, refresher);
    if (refresher) {
      refresher.complete();
    }
  }

  /**
   * 获取设备实时数据
   * @param deviceID
   * @param refresher
   */
  getDeviceInfo(deviceID, refresher?) {
    console.log(deviceID)
    this.dataservice.getDeviceInfo(deviceID).subscribe(res => {
      if (res.success) {
        this.getOneParams(res.data, deviceID).subscribe(res => {
          const data = res;
          console.log(data)
          this.deviceTypeCode = data.deviceTypeCode;
          this.deviceID = data.deviceId;
          this.deviceName = data.deviceName;
          this.projectDeviceParams = data.projectDeviceParams;
          this.onlineStatus = this.isOffLine(this.projectDeviceParams);
          console.log(this.onlineStatus)
          for (let index = 0; index < this.projectDeviceParams.length; index++) {
            const element = this.projectDeviceParams[index];
            // console.log(element)
            // 断线
            if (this.onlineStatus === 0) {
              if (element.value || element.value === 0) {
                element.value = '-';
              }
              if (element.valueName) {
                element.valueName = '-';
              }
            } else {
              if (element.roundCount >= 0) {
                element.value = element.value
                  ? parseFloat(element.value).toFixed(element.roundCount)
                  : element.value;
                element.valueName = element.valueName;
              }
            }
          }
          this.getSettingDeviceParamGroup(
            data.deviceTypeCode,
            this.projectDeviceParams,
            data.projectId,
            deviceID
          );
        });
      } else {
        // alert(res.code + ' | ' + res.message);
        console.log(res.code + ' | ' + res.message);
      }
      if (refresher) {
        refresher.complete();
      }
    });
  }

  // 获取设备实时数据
  getOneParams(data, deviceId): Observable<any> {
    return new Observable(responseObserver => {

      let deviceIdAndDeviceParam = [];
      const arr = [];
      for (const item of data.projectDeviceParams) {
        arr.push({ deviceId: item.deviceId, deviceParameterCode: item.deviceParameterId });
        deviceIdAndDeviceParam = arr;
      }
      console.log(deviceIdAndDeviceParam)
      this.dataservice.getDeviceRealParams(deviceIdAndDeviceParam).subscribe(res => {
        for (const datas of res.data.datas) {
          if (datas.deviceId === data.deviceId) {
            for (const item of data.projectDeviceParams) {
              if (datas.deviceParameterCode === item.deviceParameterId) {
                Object.assign(item, datas);
              }
            }
          }
        }
        this.dataservice.getAlarmBydeviceId(deviceId).subscribe(res => {
          console.log('参数告警', res.data)
          for (const item of res.data) {
            for (const items of data.projectDeviceParams) {
              items.alarms = [];
              if (item.deviceParameterCode === items.deviceParameterCode) {
                items.alarms.push(items);
              }
            }
          }
          responseObserver.next(data);
          responseObserver.complete();
      });
    });
  });
  }

  /**
   * 获取设备通信状态
   * @param projectDeviceParams
   */
  isOffLine(projectDeviceParams) {
    console.log(projectDeviceParams)
    for (let index = 0; index < projectDeviceParams.length; index++) {
      const element = projectDeviceParams[index];
      if (element.deviceParameterId === 9) {
        if (element.value) {
          element.value = element.value
            ? parseFloat(element.value).toFixed(element.roundCount)
            : element.value;
          if (element.value > 0) {
            return 1;
          } else {
            return 0;
          }
        } else {
          return 0;
        }
      }
    }
    return 0;
  }

  /**
   * 获取设备类型显示参数规则
   * @param devicetypeID
   * @param projectDeviceParams
   * @param projectId
   * @param deviceId
   */
  getSettingDeviceParamGroup(devicetypeID, projectDeviceParams, projectId, deviceId) {
    this.dataservice.getSettingDeviceParamGroup(devicetypeID).subscribe(res => {
      // this.hasAlarms = false;
      const data = res.data;
      let parameterGroup = [];
      const parameterGroup_Odd = []; // 整理奇数项参数
      const parameterGroup_Even = []; // 整理偶数项参数

      const parameterPosition = [];
      for (let i = 0; i < data.length; i++) {
        if (data[i].position !== 11) {
          parameterPosition.push(this.getGroupValue(data, data[i].position, projectDeviceParams, projectId, deviceId));
        }
      }
      parameterGroup = parameterPosition;
      for (let i = 0; i < parameterGroup.length; i++) {
        if (parameterGroup[i].Position % 2 === 0) {
          // 偶数项
          parameterGroup_Even.push(parameterGroup[i]);
        } else {
          // 奇数项
          parameterGroup_Odd.push(parameterGroup[i]);
        }
      }
      this.parameterGroup.parameterGroup_1 = parameterGroup_Odd;
      this.parameterGroup.parameterGroup_2 = parameterGroup_Even;
      console.log('参数显示', this.parameterGroup)
      this.parameterGroup_11 = this.getGroupValue(data, 11, projectDeviceParams, projectId, deviceId);
      console.log('获取曲线', this.parameterGroup_11)
      if (this.showParamesCurvNow) {
        this.showDeviceParamesHistoryDataCurv(this.showParamesCurvNow, [this.toDay, this.nextDay], this.Days);
      } else {
        this.showDeviceParamesHistoryDataCurv(this.parameterGroup_11, [this.toDay, this.nextDay], this.Days);
      }
      this.drawChart();
    });
  }

  /**
   * 实时数据分组
   * @param data
   * @param position
   * @param projectDeviceParams
   * @param projectId
   * @param deviceId
   */
  getGroupValue(data, position, projectDeviceParams, projectId, deviceId): DeviceParameterGroup {
    const element = this.findPosition(data, position);
    if (!element) {
      return;
    }
    const name = element.groupName;
    const len = element.settingDeviceParamGroupDetails ? element.settingDeviceParamGroupDetails.length : 0;
    const values = [];
    const datacodes = [];
    const deviceTypeId = element.deviceTypeId;
    const Position = element.position;
    for (let index = 0; index < len; index++) {
      const tmp = element.settingDeviceParamGroupDetails[index];
      const val = this.findParameterValue(
        projectDeviceParams,
        tmp.deviceParameterCode
      );
      if (val && val.value !== null) {
        values.push(val);
        datacodes.push(tmp.deviceParameterCode);
      }
    }
    let unit;
    if (values.length > 0) {
      let units = '';
      let vals = [];
      values.map(val => {
        vals.push(val.unit);
      });
      vals = this.cleardb(vals);
      for (const item of vals) {
        units = units + item + '/';
      }
      units = (units.substring(units.length - 1) === '/') ? units.substring(0, units.length - 1) : units;
      unit = units;
    }

    // 处理温湿度
    if (datacodes.length === 2 && datacodes[0] === 31 && datacodes[1] === 32 && values.length > 0) {
      const value1 = values[0];
      const value2 = values[1];
      if (value1 && value2) {
        unit = value1.unit + '/' + value2.unit;
      }
    }
    return {
      deviceTypeId: deviceTypeId,
      projectId: projectId,
      name: name,
      unit: unit,
      deviceId: deviceId,
      values: values,
      datacodes: datacodes,
      Position: Position
    };
  }

  cleardb(array) {
    const temp = [];
    for (let i = 0; i < array.length; i++) {
      if (temp.indexOf(array[i]) === -1) {
        temp.push(array[i]);
      }
    }
    return temp;
  }

  findPosition(data, position) {
    for (let index = 0; index < data.length; index++) {
      const element = data[index];
      if (element.position === position) {
        return element;
      }
    }
  }

  findParameterValue(data, parameterId): Parameter {
    // console.log(data, parameterId)
    for (let index = 0; index < data.length; index++) {
      const element = data[index];
      if (element.deviceParameterId === parameterId) {
        let hasAlarm = false;
        if (element.alarms && element.alarms.length > 0) {
          hasAlarm = true;
          this.hasAlarms = true;
        }
        return {
          value: element.valueName ? element.valueName : element.value,
          unit: element.unit ? element.unit : '',
          hasAlarm: hasAlarm
        };
      }
    }
  }

  /**
   * 显示设备数据历史曲线
   */
  showDeviceParamesHistoryDataCurv(val?: DeviceParameterGroup, startAndEndDate?, displayCount?) {
    console.log(val)
    if (val && val.values.length > 0) {
      this.titles.left = val.name + ' ' + val.unit;
      this.showParamesCurvNow = val;
      if (!startAndEndDate) {
        startAndEndDate = [this.toDay, this.nextDay];
      }
      if (!displayCount) {
        displayCount = 24;
      }
      console.log('曲线', val)
      this.dataservice.getDeviceParamesHistoryData(val.projectId, val.deviceId,
        val.datacodes, displayCount, startAndEndDate).subscribe(res => {
          const chartdata = this.formatResponse(res);
          this.options = this.echart.showDevChart(chartdata);
        });
    } else {
      this.options = this.echart.showDevChart(null);
    }
  }

  /**
   * 历史数据格式化
   * @param res
   */
  formatResponse(res) {
    const ret = [];
    const data = res.data;
    if (data && data.length > 0) {
      for (let index = 0; index < data.length; index++) {
        const element = data[index];
        const temp = {
          DataCode: element.deviceParameterId,
          DataName: element.parameterName,
          Unit: element.Unit,
          xdata: [],
          ydata: []
        };
        const points = element.point;
        if (points) {
          for (let i = 0; i < points.length; i++) {
            const point = points[i];
            temp.xdata.push(i);
            temp.ydata.push(point.y);
          }
        }
        ret.push(temp);
      }
    }
    return ret;
  }

  drawChart() {
    let label, value, unit;
    if (this.parameterGroup_11 && this.parameterGroup_11.values.length > 0) {
      label = this.parameterGroup_11.name;
      value = this.parameterGroup_11.values[0].value;
      if (value && value !== '-') {
        value = parseInt(value, 10).toFixed(0);
      } else {
        if (value === '-') {
          value = '';
        } else {
          value = '';
        }
      }
      unit = this.parameterGroup_11.values[0].unit;
    } else {
      label = '';
      value = '';
      unit = '';
    }

    if (value || value !== '') {
      this.showRateChart = true;
      const node = document.querySelector('#deviceChart');
      node.innerHTML = '';
      let options;
      options = {
        domId: 'deviceChart',
        width: 160,
        height: 160,
        img: 'assets\\imgs\\device\\' + this.deviceTypeCode + '.png',
        label: label,
        value: value,
        unit: unit,
        // color: '#25990e',
      };
      // if (options.value > 55) {
      //   options.color = 'red';
      // }

      this.chart.init(options);
    } else {
      this.showRateChart = false;
      this.circleImgSrc = 'assets\\imgs\\device\\' + this.deviceTypeCode + '.png';
    }
  }

  fixCircleImgSrc() {
    this.circleImgSrc = 'assets\\imgs\\device\\default.png';
  }

  onTimeTypeChange(evtObj) {
    const { time, timeType } = evtObj;
    const date = new Date(time), y = date.getFullYear(), m = date.getMonth();
    switch (timeType) {
      case 0: // 日
        const today = this.formatDate(date, 'yyyy-MM-dd');
        const nextday = +date + 1000 * 60 * 60 * 24;
        const nextdayStr = this.formatDate(new Date(nextday), 'yyyy-MM-dd');
        this.toDay = today;
        this.nextDay = nextdayStr;
        this.Days = 24;
        this.showDeviceParamesHistoryDataCurv(this.showParamesCurvNow, [today, nextdayStr], 24);
        break;
      case 1: // 月
        const firstDay = this.formatDate(new Date(y, m, 1), 'yyyy-MM-dd');
        const lastDay = this.formatDate(new Date(y, m + 1, 0), 'yyyy-MM-dd');
        this.toDay = firstDay;
        this.nextDay = lastDay;
        this.Days = 31;
        this.showDeviceParamesHistoryDataCurv(this.showParamesCurvNow, [firstDay, lastDay], 31);
        break;
      case 2: // 年
        const firstDayOfYear = this.formatDate(new Date(y - 1, 11, 31), 'yyyy-MM-dd');
        this.showDeviceParamesHistoryDataCurv(this.showParamesCurvNow, [firstDayOfYear, this.formatDate(date, 'yyyy-MM-dd')], 12);
        break;
      default:
        break;
    }
  }

  toShowSubPage(id) {
    console.log(id);
  }

  deviceChange(index) {
    this.showParamesCurvNow = null;
    this.toDay = this.datePipe.transform(new Date(), 'yyyy-MM-dd');
    const nextday = + new Date() + 1000 * 60 * 60 * 24;
    this.nextDay = this.formatDate(new Date(nextday), 'yyyy-MM-dd');
    this.Days = 24;
    this.state.reset = true;
    this.getDeviceInfo(this.deviceList.list[index].deviceId);
  }

  formatDate(date, fmt) {
    const o = {
      'M+': date.getMonth() + 1,                   // 月份
      'd+': date.getDate(),                        // 日
      'h+': date.getHours(),                       // 小时
      'm+': date.getMinutes(),                     // 分
      's+': date.getSeconds(),                     // 秒
      'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
      'S': date.getMilliseconds()                  // 毫秒
    };
    if (/(y+)/.test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
    }
    for (const k in o) {
      if (new RegExp('(' + k + ')').test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)));
      }
    }
    return fmt;
  }
}

